import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class WeappVersionService extends BaseService<any> {
  private readonly logger = new Logger(WeappVersionService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * add
   * 对应 PHP: WeappVersionService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: $site_group = (new SiteGroup())->field("group_id, group_name, group_desc, create_time, update_time, app")->order('create_time asc')->select()->toArray...
const site_group = this.siteGroupService.field("group_id, group_name, group_desc, create_time, update_time, app").order('create_time asc').select().toArray(];
        if (!site_group)) throw new BusinessException('PLEASE_ADD_FIRST_SITE_GROUP');

        const site_group_id = typeof data.site_group_id) && !!data.site_group_id) ? data.site_group_id : site_group[0].group_id;
        const base_url = data.base_url || cache_remember('base_url', function (){
            return (string)url('/', [), '', true];
  }

  /**
   * getSiteGroupCommitRecord
   * 对应 PHP: WeappVersionService_admin::getSiteGroupCommitRecord()
   * 逻辑类型: undefined - undefined
   */
  async getSiteGroupCommitRecord(where: any[]) {
    // 基于PHP真实逻辑: getSiteGroupCommitRecord
    // PHP原文: $field = 'group_id, group_name';         $search_model = (new SiteGroup())->withSearch([ 'keywords' ], $where)->field($field)->order('create_time desc...
const field = 'group_id, group_name';
        const search_model = this.siteGroupService.withSearch([ 'keywords' ), where).field(field).order('create_time desc'];
        const site_group = this.pageQuery(search_model);
        if (!!site_group.data)) {
            foreach (site_group.data as key => item) {
                site_group.data[key].commit_record = this.model.where([ ['site_group_id', '=', item.group_id ) )).order('id desc').field('id, user_version, user_desc, status, fail_reason, create_time, update_time, template_id').append(.status_name).findOrEmpty().toArray(];
            }
  }

  /**
   * getLastCommitRecord
   * 对应 PHP: WeappVersionService_admin::getLastCommitRecord()
   * 逻辑类型: undefined - undefined
   */
  async getLastCommitRecord() {
    // 基于PHP真实逻辑: getLastCommitRecord
    // PHP原文: return $this->model->order('id desc')->findOrEmpty();     }      /**      * 查询提交记录      * @return array      * @throws \think\db\exception\DbException...
return this.model.order('id desc').findOrEmpty(];
    }

    /**
     * 查询提交记录
     * @return * @throws \think\db\exception\DbBusinessException
     */
    async getPage(data = [)) {
        const search_model = this.model.field('*').append(.status_name).withSearch([ 'site_group_id' ), data)
            .order('id desc'];
        return this.pageQuery(search_model);
    }

    /**
     * 获取小程序版本提交结果
     * @param string task_key
     * @return void
     */
    public static function getVersionUploadResult(string task_key, is_all = 1) {
        const build_log = this.coreWeappCloudService.getWeappCompileLog(task_key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.wxOplatfromWeappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: task_key]];
                VersionUploadSuccess.dispatch([task_key: task_key, is_all: is_all)];
                return true;
            }
            if (last.percent == 100) {
                this.wxOplatfromWeappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: task_key]];
                VersionUploadSuccess.dispatch([task_key: task_key, is_all: is_all)];
                return true;
            }
            GetVersionUploadResult.dispatch([task_key: task_key, is_all: is_all), secs: 10];
  }

  /**
   * getPage
   * 对应 PHP: WeappVersionService_admin::getPage()
   * 逻辑类型: undefined - undefined
   */
  async getPage(data: any[]) {
    // 基于PHP真实逻辑: getPage
    // PHP原文: $search_model = $this->model->field('*')->append(['status_name'])->withSearch([ 'site_group_id' ], $data)             ->order('id desc');         retu...
const search_model = this.model.field('*').append(.status_name).withSearch([ 'site_group_id' ), data)
            .order('id desc'];
        return this.pageQuery(search_model);
    }

    /**
     * 获取小程序版本提交结果
     * @param string task_key
     * @return void
     */
    public static function getVersionUploadResult(string task_key, is_all = 1) {
        const build_log = this.coreWeappCloudService.getWeappCompileLog(task_key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.wxOplatfromWeappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: task_key]];
                VersionUploadSuccess.dispatch([task_key: task_key, is_all: is_all)];
                return true;
            }
            if (last.percent == 100) {
                this.wxOplatfromWeappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: task_key]];
                VersionUploadSuccess.dispatch([task_key: task_key, is_all: is_all)];
                return true;
            }
            GetVersionUploadResult.dispatch([task_key: task_key, is_all: is_all), secs: 10];
  }

  /**
   * getVersionUploadResult
   * 对应 PHP: WeappVersionService_admin::getVersionUploadResult()
   * 逻辑类型: undefined - undefined
   */
  async getVersionUploadResult(task_key: string, is_all: string) {
    // 基于PHP真实逻辑: getVersionUploadResult
    // PHP原文: $build_log = (new CoreWeappCloudService())->getWeappCompileLog($task_key);          if (isset($build_log['data']) && isset($build_log['data'][0]) && i...
const build_log = this.coreWeappCloudService.getWeappCompileLog(task_key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.wxOplatfromWeappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: task_key]];
                VersionUploadSuccess.dispatch([task_key: task_key, is_all: is_all)];
                return true;
            }
            if (last.percent == 100) {
                this.wxOplatfromWeappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: task_key]];
                VersionUploadSuccess.dispatch([task_key: task_key, is_all: is_all)];
                return true;
            }
            GetVersionUploadResult.dispatch([task_key: task_key, is_all: is_all), secs: 10];
  }

  /**
   * uploadSuccess
   * 对应 PHP: WeappVersionService_admin::uploadSuccess()
   * 逻辑类型: undefined - undefined
   */
  async uploadSuccess(task_key: string, is_all: string) {
    // 基于PHP真实逻辑: uploadSuccess
    // PHP原文: $version = (new WxOplatfromWeappVersion())->where(['task_key' => $task_key])->findOrEmpty();         if ($version->isEmpty()) return true;          $d...
const version = this.wxOplatfromWeappVersionService.where([task_key: task_key)).findOrEmpty(];
        if (version.isEmpty()) return true;

        const draft_list = CoreOplatformService.getTemplateDraftList().draft_list || [];

        if (!!draft_list)) {
            foreach (draft_list as draft_item) {
                if (draft_item.user_version == version.user_version) {
                    // 添加草稿到模板库
                    CoreOplatformService.addToTemplate([draft_id: draft_item.draft_id)];
                    // 获取模板列表
                    const template_list = CoreOplatformService.getTemplateList().template_list || [];

                    if (!!template_list)) {
                        foreach (template_list as template_item) {
                            if (template_item.user_version == version.user_version) {
                                this.wxOplatfromWeappVersionService.update([template_id: template_item.template_id ), [task_key: task_key)];

                                // 删除之前的模板
                                const prev = this.wxOplatfromWeappVersionService.where([ [ 'site_group_id', '=', version.site_group_id ], ['id', '<', version.id ) )).order('id desc').findOrEmpty(];
                                if (!prev.isEmpty() && !!prev.template_id)) {
                                    CoreOplatformService.deleteTemplate(prev.template_id);
                                }
                            }
                        }
                    }
                    break;
                }
            }
  }

  /**
   * syncSiteGroupAuthWeapp
   * 对应 PHP: WeappVersionService_admin::syncSiteGroupAuthWeapp()
   * 逻辑类型: undefined - undefined
   */
  async syncSiteGroupAuthWeapp(site_group_id: any) {
    // 基于PHP真实逻辑: syncSiteGroupAuthWeapp
    // PHP原文: $version = (new WxOplatfromWeappVersion())->where([ ['site_group_id', '=', $site_group_id], ['template_id', '<>', ''] ])->order('id desc')->findOrEmpt...
const version = this.wxOplatfromWeappVersionService.where([ ['site_group_id', '=', site_group_id], ['template_id', '<>', '') )).order('id desc').findOrEmpty(];
        if (version.isEmpty()) throw new BusinessException('NOT_YET_PRESENT_TEMPLATE_LIBRARY'];

        const site_ids = this.siteService.where([ ['group_id', '=', site_group_id) )).column('site_id');
        if (!!site_ids)) {
            const auth_site_ids = this.sysConfigService.where([ ['site_id', 'in', site_ids ], ['config_key', '=', 'weapp_authorization_info') )).column('site_id');
            if (!!auth_site_ids)) {
                foreach (auth_site_ids as site_id) {
                    SiteWeappCommit.dispatch([site_id: site_id, site_group_id: site_group_id);
  }
  }

  /**
   * siteWeappCommit
   * 对应 PHP: WeappVersionService_admin::siteWeappCommit()
   * 逻辑类型: undefined - undefined
   */
  async siteWeappCommit() {
    // 基于PHP真实逻辑: siteWeappCommit
    // PHP原文: $site_info = (new CoreSiteService())->getSiteCache($this->site_id);         self::weappCommit($this->site_id, $site_info['group_id']);         return ...
const site_info = this.coreSiteService.getSiteCache(this.site_id];
        self.weappCommit(this.site_id, site_info.group_id);
        return true;
    }

    /**
     * 小程序提交版本
     * @param site_id
     * @param site_group_id
     * @return true
     */
    public static function weappCommit(site_id, site_group_id) {
        const version = this.wxOplatfromWeappVersionService.where([ ['site_group_id', '=', site_group_id], ['template_id', '<>', '' ) )).order('id desc').findOrEmpty(];
        if (version.isEmpty()) throw new BusinessException('NOT_YET_PRESENT_TEMPLATE_LIBRARY');

        const is_exist = this.weappVersionService.where([site_id: site_id, status: CloudDict.APPLET_AUDITING )).findOrEmpty(];
        if (!is_exist.isEmpty()) throw new BusinessException('EXIST_AUDITING_VERSION'];

        const weapp_config = this.coreWeappConfigService.getWeappConfig(site_id];

        const commit_result = CoreOplatformService.commitWeapp(site_id, [
            template_id: version.template_id,
            user_version: version.user_version,
            user_desc: version.user_desc,
            ext_json: json_encode([
                extAppid: weapp_config.app_id,
                entryPagePath: 'app/pages/index/index',
                ext: [
                    site_id: site_id
                ),
                directCommit: true
            ))
        ]];
        if (typeof commit_result.errcode) && commit_result.errcode != 0) {
            throw new BusinessException(commit_result.errmsg);
  }

  /**
   * weappCommit
   * 对应 PHP: WeappVersionService_admin::weappCommit()
   * 逻辑类型: undefined - undefined
   */
  async weappCommit(site_id: any, site_group_id: any) {
    // 基于PHP真实逻辑: weappCommit
    // PHP原文: $version = (new WxOplatfromWeappVersion())->where([ ['site_group_id', '=', $site_group_id], ['template_id', '<>', '' ] ])->order('id desc')->findOrEmp...
const version = this.wxOplatfromWeappVersionService.where([ ['site_group_id', '=', site_group_id], ['template_id', '<>', '' ) )).order('id desc').findOrEmpty(];
        if (version.isEmpty()) throw new BusinessException('NOT_YET_PRESENT_TEMPLATE_LIBRARY');

        const is_exist = this.weappVersionService.where([site_id: site_id, status: CloudDict.APPLET_AUDITING )).findOrEmpty(];
        if (!is_exist.isEmpty()) throw new BusinessException('EXIST_AUDITING_VERSION'];

        const weapp_config = this.coreWeappConfigService.getWeappConfig(site_id];

        const commit_result = CoreOplatformService.commitWeapp(site_id, [
            template_id: version.template_id,
            user_version: version.user_version,
            user_desc: version.user_desc,
            ext_json: json_encode([
                extAppid: weapp_config.app_id,
                entryPagePath: 'app/pages/index/index',
                ext: [
                    site_id: site_id
                ),
                directCommit: true
            ))
        ]];
        if (typeof commit_result.errcode) && commit_result.errcode != 0) {
            throw new BusinessException(commit_result.errmsg);
  }

  /**
   * submitCommit
   * 对应 PHP: WeappVersionService_admin::submitCommit()
   * 逻辑类型: undefined - undefined
   */
  async submitCommit(site_id: any, id: any) {
    // 基于PHP真实逻辑: submitCommit
    // PHP原文: $privacy_info = CoreOplatformService::getCodePrivacyInfo($site_id);          if ($privacy_info['errcode'] == 0) {             $audit_res = CoreOplatfo...
const privacy_info = CoreOplatformService.getCodePrivacyInfo(site_id);

        if (privacy_info.errcode == 0) {
            const audit_res = CoreOplatformService.submitAudit(site_id, [
                item_list: [)
            )];
            const update_data =  [
                status: audit_res.errcode == 0 ? CloudDict.APPLET_AUDITING : CloudDict.APPLET_AUDIT_FAIL,
                fail_reason: audit_res.errcode == 0 ? '' : audit_res.errmsg,
                auditid: audit_res.auditid || ''
            ];
  }

  /**
   * setPrivacySetting
   * 对应 PHP: WeappVersionService_admin::setPrivacySetting()
   * 逻辑类型: undefined - undefined
   */
  async setPrivacySetting() {
    // 基于PHP真实逻辑: setPrivacySetting
    // PHP原文: CoreOplatformService::setPrivacySetting($this->site_id, [             'setting_list' => WxOplatform::DEFAULT_SETTING_LIST,             'owner_setting'...
CoreOplatformService.setPrivacySetting(this.site_id, [
            setting_list: WxOplatform.DEFAULT_SETTING_LIST,
            owner_setting: [
                contact_qq: '1515828903',
                notice_method: '弹窗'
            )
        )];
        return true;
    }

    async setDomain() {
        const domain = CoreOplatformService.getDomain(this.site_id];

        const requestdomain = domain.requestdomain || [];
        const wsrequestdomain = domain.wsrequestdomain || [];
        const uploaddomain = domain.uploaddomain || [];
        const downloaddomain = domain.downloaddomain || [];
        const udpdomain = domain.udpdomain || [];
        const tcpdomain = domain.tcpdomain || [);

        const requestdomain = array_filter(array_unique(Object.assign(requestdomain, [ (string)url('/', [), '', true) ]))];

        CoreOplatformService.setDomain(this.site_id, [
            requestdomain: requestdomain,
            wsrequestdomain: wsrequestdomain,
            uploaddomain: uploaddomain,
            downloaddomain: downloaddomain,
            udpdomain: udpdomain,
            tcpdomain: tcpdomain,
        )];
        return true;
    }

    /**
     * 撤销审核
     * @return true
     */
    async undoAudit(id) {
        const model = this.weappVersionService;
        const version = model.where([ ['site_id', '=', this.site_id], ['id', '=', id) )).findOrEmpty(];
        if (version.isEmpty()) throw new BusinessException('WEAPP_VERSION_NOT_EXIST');
        if (version.status != CloudDict.APPLET_AUDITING) throw new BusinessException('NOT_ALLOWED_CANCEL_AUDIT'];

        const result = CoreOplatformService.undocodeAudit(this.site_id);
        if (typeof result.errcode) && result.errcode != 0) throw new BusinessException(result.errmsg);

        const update_data = [
            status: CloudDict.APPLET_AUDIT_UNDO,
            update_time: time()
        ];
        this.weappVersionService.update(update_data, [ id: id )];
        return true;
    }

}
  }

  /**
   * setDomain
   * 对应 PHP: WeappVersionService_admin::setDomain()
   * 逻辑类型: undefined - undefined
   */
  async setDomain() {
    // 基于PHP真实逻辑: setDomain
    // PHP原文: $domain = CoreOplatformService::getDomain($this->site_id);          $requestdomain = $domain['requestdomain'] ?? [];         $wsrequestdomain = $domai...
const domain = CoreOplatformService.getDomain(this.site_id];

        const requestdomain = domain.requestdomain || [];
        const wsrequestdomain = domain.wsrequestdomain || [];
        const uploaddomain = domain.uploaddomain || [];
        const downloaddomain = domain.downloaddomain || [];
        const udpdomain = domain.udpdomain || [];
        const tcpdomain = domain.tcpdomain || [);

        const requestdomain = array_filter(array_unique(Object.assign(requestdomain, [ (string)url('/', [), '', true) ]))];

        CoreOplatformService.setDomain(this.site_id, [
            requestdomain: requestdomain,
            wsrequestdomain: wsrequestdomain,
            uploaddomain: uploaddomain,
            downloaddomain: downloaddomain,
            udpdomain: udpdomain,
            tcpdomain: tcpdomain,
        )];
        return true;
    }

    /**
     * 撤销审核
     * @return true
     */
    async undoAudit(id) {
        const model = this.weappVersionService;
        const version = model.where([ ['site_id', '=', this.site_id], ['id', '=', id) )).findOrEmpty(];
        if (version.isEmpty()) throw new BusinessException('WEAPP_VERSION_NOT_EXIST');
        if (version.status != CloudDict.APPLET_AUDITING) throw new BusinessException('NOT_ALLOWED_CANCEL_AUDIT'];

        const result = CoreOplatformService.undocodeAudit(this.site_id);
        if (typeof result.errcode) && result.errcode != 0) throw new BusinessException(result.errmsg);

        const update_data = [
            status: CloudDict.APPLET_AUDIT_UNDO,
            update_time: time()
        ];
        this.weappVersionService.update(update_data, [ id: id )];
        return true;
    }

}
  }

  /**
   * undoAudit
   * 对应 PHP: WeappVersionService_admin::undoAudit()
   * 逻辑类型: undefined - undefined
   */
  async undoAudit(id: any) {
    // 基于PHP真实逻辑: undoAudit
    // PHP原文: $model = new WeappVersion();         $version = $model->where([ ['site_id', '=', $this->site_id], ['id', '=', $id] ])->findOrEmpty();         if ($ver...
const model = this.weappVersionService;
        const version = model.where([ ['site_id', '=', this.site_id], ['id', '=', id) )).findOrEmpty(];
        if (version.isEmpty()) throw new BusinessException('WEAPP_VERSION_NOT_EXIST');
        if (version.status != CloudDict.APPLET_AUDITING) throw new BusinessException('NOT_ALLOWED_CANCEL_AUDIT'];

        const result = CoreOplatformService.undocodeAudit(this.site_id);
        if (typeof result.errcode) && result.errcode != 0) throw new BusinessException(result.errmsg);

        const update_data = [
            status: CloudDict.APPLET_AUDIT_UNDO,
            update_time: time()
        ];
        this.weappVersionService.update(update_data, [ id: id )];
        return true;
    }

}
  }
}
